<?php
/**
 * Created by PhpStorm.
 * User: trisatria
 * Date: 1/7/14
 * Time: 11:04 AM
 */

namespace Admin\Model;
use stdClass;
use Admin\Model\AdminUser;
use Zend\Db\Sql\Select;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Authentication\Result as AuthenticationResult;
use Zend\Authentication\AuthenticationService;


class AdminUserTable  implements  AdapterInterface
{
    protected $tableGateway;
    protected $loginUser;


    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }


    public function getLoginUser(){
        return $this->getLoginUser();
    }




    public function setLoginUser($user = array()){
        $this->loginUser = $user;
    }




    public function fetchAll()
    {
        $select = new Select('user');
        // create a new result set based on the Album entity
        $resultSetPrototype = new ResultSet();
        $resultSetPrototype->setArrayObjectPrototype(new AdminUser());
        // create a new pagination adapter object
        $paginatorAdapter = new DbSelect(
        // our configured select object
            $select,
            // the adapter to run it against
            $this->tableGateway->getAdapter(),
            // the result set to hydrate
            $resultSetPrototype
        );
        $paginator = new Paginator($paginatorAdapter);
        return $paginator;
    }



    public function getUser($id)
    {
        $id  = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            return null;
        }
        return $row;
    }



    public function getLastIdInsert(){
        return $this->tableGateway->lastInsertValue;
    }



    public function getUserByEmail($email){
        $rowset = $this->tableGateway->select(array('email' => $email));
        $row = $rowset->current();
        return $row;
    }


    public function saveUser(AdminUser $user)
    {
        $data = array(
            'name' => $user->name,
            'email'  => $user->email,
            'address'  => $user->address,
            'phone' => $user->phone,
            'avatar'  => $user->avatar,
            'password'  => $user->password,
            'time_reg' => $user->time_reg,
            'status' => $user->status,
            'user_type' => $user->user_type,
            'confirm' => $user->confirm,
            'yahooid' => $user->yahooid,
            'skypeid' => $user->skypeid,
            'birthday' => $user->birthday,
            'telephone' => $user->telephone,
            'zalo' => $user->zalo,
            'viber' => $user->viber,
            'kakaotalk' => $user->kakaotalk,
        );

        $id = (int)$user->id;
        if ($id == 0) {
            if ($this->tableGateway->insert($data)) return $this->tableGateway->getLastInsertValue();
            else return false;
        } else {
            if ($this->getUser($id)) {
                if ($this->tableGateway->update($data, array('id' => $id))) return true;
                else return false;
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
    }


    public function save($data = array(),$where = array()){
       return  $this->tableGateway->update($data, $where);

    }

    /* thay doi mat khau*/

    public function changeUserPass($password= null){
        $result = false;
        $auth = new AuthenticationService();

        $id = $auth->getIdentity()->userid;
        $email = $auth->getIdentity()->email;
        $user = $this->getUserByEmail($email);
        $old_pass = md5($email.$password['old_pass']);
        $new_pass = md5($email.$password['password']);
        if($old_pass == $user->password){
               $this->save(array(
                   'password'=>$new_pass
               ),
                   array(
                   'id'=>$id
                   ));
            $result = true;
        }else{
            $result = false;
        }
        return $result;

    }


    public function deleteUser($id)
    {
        $this->tableGateway->delete(array('id' => $id));
    }



    public function authenticate(){
        if( !isset($this->loginUser['password'])){
             $result = $this->loginFacebook($this->loginUser['username']);
        }else{
            $result = $this->login($this->loginUser['username'],md5($this->loginUser['username'].$this->loginUser['password']));

        }

        if( $result ){
            $identity = new stdClass();
            $identity->userid = $result->id;
            $identity->email = $result->email;
            $identity->name = $result->name;
            $identity->password = $result->password;
            $identity->address = $result->address;
            $identity->phone = $result->phone;
            $identity->avatar = $result->avatar;
            $identity->status = $result->status;
            $identity->user_type = $result->user_type;
            $identity->time_reg = $result->time_reg;
            $identity->confirm = $result->confirm;
            $identity->yahooid = $result->yahooid;
            $identity->skypeid = $result->skypeid;
            $identity->birthday = $result->birthday;
            $identity->telephone = $result->telephone;
            $identity->zalo = $result->zalo;
            $identity->viber = $result->viber;
            $identity->kakaotalk = $result->kakaotalk;
            return new AuthenticationResult(
                AuthenticationResult::SUCCESS,
                $identity,
                array()
            );
        }else{
            return new AuthenticationResult(
                AuthenticationResult::FAILURE,
                null,
                array('error'=>'Login Fail'));

        }

    }



    public function loginFacebook($username){
        $user = $this->getUserByEmail($username);
        if($user){
            return $user;
        }
        return null;
    }



    public function login($username, $password){
        $user = $this->getUserByEmail($username);

        if($user){
            if($password == $user->password){
                return $user;
            }
        }
        return null;
    }



    public function searchFullText($val)
    {
        $select = new Select();
        $select->columns(array('*',new \Zend\Db\Sql\Expression("MATCH(name, email, address, phone) AGAINST('".$val."') AS score")));
        $select->from('user');
        $select->where(' MATCH(name, email, address, phone) AGAINST ("'.$val.'")');
        $select->order('score DESC');

        $resultSetPrototype = new ResultSet();
        $resultSetPrototype->setArrayObjectPrototype(new AdminUser());
        //echo $select->getSqlString();
        // create a new pagination adapter object
        $paginatorAdapter = new DbSelect(
        // our configured select object
            $select,
            // the adapter to run it against
            $this->tableGateway->getAdapter(),
            // the result set to hydrate
            $resultSetPrototype
        );
        $paginator = new Paginator($paginatorAdapter);
        return $paginator;
    }
    public function searchFullTextArray($val){
        $str = "SELECT *, MATCH(name, email, address, phone) AGAINST('".$val."') AS score FROM `user` WHERE  MATCH(name, email, address, phone) AGAINST ('".$val."') ORDER BY score DESC ";
        $driver = $this->tableGateway->getAdapter()->getDriver();
        $connection = $driver->getConnection();
        $result = $connection->execute($str);
        $statement = $result->getResource();
        $resultSet1 = $statement->fetchAll(\Pdo::FETCH_NAMED);
        // $resultSet1 = $statement->fetchAll(\Pdo::FETCH_OBJ);
        return $resultSet1;
    }

    public function getUserWhere($where = array()){
        $where_sql = '';
        $i = 0;
        foreach($where as $key => $value){
            $i++;
            if($i==1){
                $where_sql .= " `".$key."` = '".$value."' " ;
            }
            if($i>1){

                $where_sql .= " AND `".$key."` =  '".$value."' ";

            }
        }
        $str = " SELECT * FROM user WHERE ".$where_sql;
        $driver = $this->tableGateway->getAdapter()->getDriver();
        $connection = $driver->getConnection();
        $result = $connection->execute($str);

        $statement = $result->getResource();
        $resultSet1 = $statement->fetchAll(\Pdo::FETCH_NAMED);
        // $resultSet1 = $statement->fetchAll(\Pdo::FETCH_OBJ);
        return $resultSet1;
    }
}